package com.aivin.maproutelib.line;

import com.aivin.maproutelib.bean.WaypointInfo;

/**
 * 一条辅助线 ，两个点边界拐点 组成的线。
 */
public class HelperLine {

    public WaypointInfo startPoint;
    public WaypointInfo endPoint;
    private double maxX;
    private double minX;

    /**
     * y = k * x + b
     * 线的K值，斜率
     */
    public double k;
    /**
     * y = k * x + b ,b
     */
    public double b;


    public HelperLine(WaypointInfo startPoint, WaypointInfo endPoint) {
        startPoint.addAlinePassedThePoint(this);
        endPoint.addAlinePassedThePoint(this);

        this.startPoint = startPoint;
        this.endPoint = endPoint;
        init(startPoint, endPoint);
    }


    private void init(WaypointInfo startPoint, WaypointInfo endPoint) {
        double deltaX = endPoint.getLatitude() - startPoint.getLatitude();
        double deltaY = endPoint.getLongitude() - startPoint.getLongitude();

        if (deltaY == 0) {
            deltaY = 0.000000001f;
            endPoint.setLongitude(endPoint.getLongitude() + 0.000000001f);
        }

        if (deltaX == 0) {
            deltaX = 0.000000001f;
            endPoint.setLatitude(endPoint.getLatitude() + 0.000000001f);
        }

        k = deltaY / deltaX;
        b = startPoint.getLongitude() - k * startPoint.getLatitude();

        minX = Math.min(startPoint.getLatitude(), endPoint.getLatitude());
        maxX = Math.max(startPoint.getLatitude(), endPoint.getLatitude());
    }


    /**
     * y = k * x + b
     */
    public double getY(double x) {
        return (k * x + b);
    }

    /**
     * 指定的x值是否在两点之间的 x 区间内
     */
    public boolean isInXRange(double x) {
        return x >= minX && x <= maxX;
    }


    /**
     * 获取该线的对齐角度
     */
    public float getRotate(WaypointInfo point) {
        float degree = (float) Math.toDegrees(Math.atan(k));

        WaypointInfo p = null;
        if (point.equals(startPoint)) {
            p = endPoint;
        } else if (point.equals(endPoint)) {
            p = startPoint;
        }

        if(p==null){
            throw new RuntimeException("角度获取异常...") ;
        }

        if (p.getLongitude() < point.getLongitude()) {
            if (p.getLatitude() < point.getLatitude()) {
                degree = degree + 180;
            }
        } else {
            if (p.getLatitude() < point.getLatitude()) {
                degree = degree + 180;
            }
        }

        return degree < 0 ? degree + 360 : degree;
    }


}
